<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div class="favorites-page">
    <div class="page-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-left">
          <el-button @click="$router.back()" :icon="ArrowLeft" circle />
          <div class="header-info">
            <h1>我的收藏</h1>
            <p>管理您收藏的剪纸文化、教程和资讯内容</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button @click="showBatchActions = !showBatchActions" :icon="Operation">
            批量管理
          </el-button>
          <el-dropdown @command="handleSort">
            <el-button :icon="Sort">
              排序 <el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="createTime">最近收藏</el-dropdown-item>
                <el-dropdown-item command="title">按标题</el-dropdown-item>
                <el-dropdown-item command="type">按类型</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stats-grid">
          <div class="stat-card total" @click="activeTab = 'all'">
            <div class="stat-icon">
              <el-icon><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ totalCount }}</div>
              <div class="stat-label">总收藏</div>
            </div>
          </div>
          
          <div class="stat-card culture" @click="activeTab = 'culture'">
            <div class="stat-icon">
              <el-icon><DocumentCopy /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ cultureCount }}</div>
              <div class="stat-label">剪纸文化</div>
            </div>
          </div>

          <div class="stat-card tutorial" @click="activeTab = 'tutorial'">
            <div class="stat-icon">
              <el-icon><VideoPlay /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ tutorialCount }}</div>
              <div class="stat-label">教程学习</div>
            </div>
          </div>

          <div class="stat-card news" @click="activeTab = 'news'">
            <div class="stat-icon">
              <el-icon><Bell /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-number">{{ newsCount }}</div>
              <div class="stat-label">活动资讯</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 批量操作栏 -->
      <div class="batch-actions" v-show="showBatchActions">
        <div class="batch-left">
          <el-checkbox
            v-model="selectAll"
            :indeterminate="indeterminate"
            @change="handleSelectAll"
          >
            全选
          </el-checkbox>
          <span class="selected-count">已选择 {{ selectedItems.length }} 项</span>
        </div>
        <div class="batch-right">
          <el-button 
            type="danger" 
            :icon="Delete" 
            :disabled="selectedItems.length === 0"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
          <el-button @click="cancelBatchActions">取消</el-button>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-section">
        <!-- 分类标签 -->
        <div class="filter-tabs">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange">
            <el-tab-pane label="全部" name="all" />
            <el-tab-pane label="剪纸文化" name="culture" />
            <el-tab-pane label="教程学习" name="tutorial" />
            <el-tab-pane label="活动资讯" name="news" />
          </el-tabs>
        </div>

        <!-- 收藏列表 -->
        <div class="favorites-content" v-loading="loading">
          <!-- 无数据 -->
          <div class="no-data" v-if="!loading && currentList.length === 0">
            <el-empty description="暂无收藏内容">
              <el-button type="primary" @click="$router.push('/')">
                去首页看看
              </el-button>
            </el-empty>
          </div>

          <!-- 数据列表 -->
          <div class="favorites-grid" v-if="currentList.length > 0">
            <div
              v-for="item in currentList"
              :key="item.id"
              class="favorite-item"
              :class="{ 'selected': selectedItems.includes(item.id) }"
            >
              <!-- 选择框 -->
              <div class="item-checkbox" v-show="showBatchActions">
                <el-checkbox
                  :model-value="selectedItems.includes(item.id)"
                  @change="handleItemSelect(item.id, $event)"
                />
              </div>

              <!-- 内容卡片 -->
              <div class="item-card" @click="handleItemClick(item)">
                <div class="card-image">
                  <img :src="getItemImage(item)" :alt="getItemTitle(item)" />
                  <div class="type-badge" :class="`type-${item.targetType}`">
                    {{ getTypeName(item.targetType) }}
                  </div>
                </div>
                
                <div class="card-content">
                  <h3>{{ getItemTitle(item) }}</h3>
                  <p>{{ getItemSummary(item) }}</p>
                  
                  <!-- 元信息 -->
                  <div class="item-meta">
                    <div class="meta-info">
                      <span class="collect-time">{{ formatDate(item.createTime) }}</span>
                      <span class="item-type">{{ getTypeName(item.targetType) }}</span>
                    </div>
                    <div class="item-actions">
                      <el-button
                        size="small"
                        type="primary"
                        @click.stop="handleItemClick(item)"
                        :icon="View"
                      >
                        查看
                      </el-button>
                      <el-button
                        size="small"
                        type="danger"
                        @click.stop="handleRemoveFavorite(item)"
                        :icon="Delete"
                      >
                        取消收藏
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载更多 -->
          <div class="load-more" v-if="hasMore && currentList.length > 0">
            <el-button @click="loadMore" :loading="loadingMore">
              加载更多
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="showDeleteDialog" title="确认删除" width="400px">
      <div class="delete-content">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <div class="delete-text">
          <p>确定要取消收藏这些内容吗？</p>
          <p class="delete-count">共 {{ deleteItems.length }} 项</p>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showDeleteDialog = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete" :loading="deleting">
            确定删除
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft, Operation, Sort, ArrowDown, Collection, DocumentCopy, VideoPlay, Bell,
  Delete, View, Warning
} from '@element-plus/icons-vue'
import { userFavoriteApi } from '@/api'
import type { UserFavorite } from '@/types/common'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const loadingMore = ref(false)
const showBatchActions = ref(false)
const showDeleteDialog = ref(false)
const deleting = ref(false)
const activeTab = ref('all')
const sortBy = ref('createTime')

const favoritesList = ref<UserFavorite[]>([])
const selectedItems = ref<number[]>([])
const deleteItems = ref<UserFavorite[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const hasMore = ref(true)

// 统计数据
const totalCount = computed(() => favoritesList.value.length)
const cultureCount = computed(() => favoritesList.value.filter(item => item.targetType === 'culture').length)
const tutorialCount = computed(() => favoritesList.value.filter(item => item.targetType === 'tutorial').length)
const newsCount = computed(() => favoritesList.value.filter(item => item.targetType === 'news').length)

// 当前显示列表
const currentList = computed(() => {
  let filtered = favoritesList.value
  
  // 按类型筛选
  if (activeTab.value !== 'all') {
    filtered = filtered.filter(item => item.targetType === activeTab.value)
  }
  
  // 排序
  filtered = [...filtered].sort((a, b) => {
    switch (sortBy.value) {
      case 'createTime':
        return new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
      case 'title':
        return getItemTitle(a).localeCompare(getItemTitle(b))
      case 'type':
        return a.targetType.localeCompare(b.targetType)
      default:
        return 0
    }
  })
  
  return filtered
})

// 批量选择状态
const selectAll = computed({
  get: () => selectedItems.value.length === currentList.value.length && currentList.value.length > 0,
  set: (value) => {
    if (value) {
      selectedItems.value = currentList.value.map(item => item.id)
    } else {
      selectedItems.value = []
    }
  }
})

const indeterminate = computed(() => 
  selectedItems.value.length > 0 && selectedItems.value.length < currentList.value.length
)

// 获取收藏列表
const fetchFavorites = async (reset = false) => {
  if (reset) {
    currentPage.value = 1
    favoritesList.value = []
    hasMore.value = true
  }

  loading.value = reset
  loadingMore.value = !reset

  try {
    const response = await userFavoriteApi.getFavoriteList()
    
    if (reset) {
      favoritesList.value = response.data
    } else {
      favoritesList.value.push(...response.data)
    }

    // 简化分页逻辑，实际应该根据后端分页实现
    hasMore.value = false
    currentPage.value++
  } catch (error) {
    ElMessage.error('获取收藏列表失败')
  } finally {
    loading.value = false
    loadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loadingMore.value) return
  fetchFavorites(false)
}

// 标签页切换
const handleTabChange = (tab: string) => {
  activeTab.value = tab
  selectedItems.value = []
}

// 排序
const handleSort = (command: string) => {
  sortBy.value = command
}

// 项目选择
const handleItemSelect = (itemId: number, checked: boolean) => {
  if (checked) {
    selectedItems.value.push(itemId)
  } else {
    selectedItems.value = selectedItems.value.filter(id => id !== itemId)
  }
}

// 全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedItems.value = currentList.value.map(item => item.id)
  } else {
    selectedItems.value = []
  }
}

// 取消批量操作
const cancelBatchActions = () => {
  showBatchActions.value = false
  selectedItems.value = []
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedItems.value.length === 0) return
  
  deleteItems.value = favoritesList.value.filter(item => selectedItems.value.includes(item.id))
  showDeleteDialog.value = true
}

// 单个取消收藏
const handleRemoveFavorite = (item: UserFavorite) => {
  deleteItems.value = [item]
  showDeleteDialog.value = true
}

// 确认删除
const confirmDelete = async () => {
  deleting.value = true
  
  try {
    // 批量删除收藏
    for (const item of deleteItems.value) {
      await userFavoriteApi.toggleFavorite(item.targetType, item.targetId)
    }

    // 从列表中移除
    const deleteIds = deleteItems.value.map(item => item.id)
    favoritesList.value = favoritesList.value.filter(item => !deleteIds.includes(item.id))
    selectedItems.value = []

    ElMessage.success(`成功取消收藏 ${deleteItems.value.length} 项内容`)
    showDeleteDialog.value = false
  } catch (error) {
    ElMessage.error('取消收藏失败')
  } finally {
    deleting.value = false
    deleteItems.value = []
  }
}

// 点击项目
const handleItemClick = (item: UserFavorite) => {
  if (showBatchActions.value) return
  
  const routes = {
    culture: `/culture/${item.targetId}`,
    tutorial: `/tutorial/${item.targetId}`,
    news: `/news/${item.targetId}`
  }
  
  const route = routes[item.targetType as keyof typeof routes]
  if (route) {
    router.push(route)
  }
}

// 工具函数
const getItemImage = (item: UserFavorite) => {
  return item.content?.coverImage || `/default-${item.targetType}.jpg`
}

const getItemTitle = (item: UserFavorite) => {
  return item.content?.title || '标题'
}

const getItemSummary = (item: UserFavorite) => {
  return item.content?.summary || '暂无简介'
}

const getTypeName = (type: string) => {
  const typeNames = {
    culture: '剪纸文化',
    tutorial: '教程学习',
    news: '活动资讯'
  }
  return typeNames[type as keyof typeof typeNames] || type
}

const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天收藏'
  } else if (days === 1) {
    return '昨天收藏'
  } else if (days < 7) {
    return `${days}天前收藏`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

onMounted(() => {
  fetchFavorites(true)
})
</script>

<style scoped>
.favorites-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  background: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-info h1 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 4px;
}

.header-info p {
  color: #666;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: 1px solid #f0f0f0;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border-color: #d32f2f;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.stat-card.total .stat-icon {
  background: #2196f3;
}

.stat-card.culture .stat-icon {
  background: #d32f2f;
}

.stat-card.tutorial .stat-icon {
  background: #43a047;
}

.stat-card.news .stat-icon {
  background: #ff9800;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

/* 批量操作栏 */
.batch-actions {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px 20px;
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.batch-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.selected-count {
  color: #666;
  font-size: 14px;
}

.batch-right {
  display: flex;
  gap: 12px;
}

/* 内容区域 */
.content-section {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.filter-tabs {
  padding: 0 24px;
  border-bottom: 1px solid #f0f0f0;
}

.favorites-content {
  padding: 24px;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
}

/* 收藏网格 */
.favorites-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.favorite-item {
  position: relative;
  border: 2px solid transparent;
  border-radius: 12px;
  transition: all 0.3s;
}

.favorite-item.selected {
  border-color: #2196f3;
  background: #f0f8ff;
}

.item-checkbox {
  position: absolute;
  top: 12px;
  left: 12px;
  z-index: 10;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 4px;
  padding: 4px;
}

.item-card {
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.card-image {
  position: relative;
  height: 150px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.item-card:hover .card-image img {
  transform: scale(1.05);
}

.type-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
  color: #fff;
}

.type-badge.type-culture {
  background: #d32f2f;
}

.type-badge.type-tutorial {
  background: #43a047;
}

.type-badge.type-news {
  background: #2196f3;
}

.card-content {
  padding: 16px;
}

.card-content h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

.card-content p {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  margin-bottom: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.item-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.meta-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.collect-time,
.item-type {
  font-size: 12px;
  color: #999;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.load-more {
  text-align: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}

/* 删除确认对话框 */
.delete-content {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 0;
}

.warning-icon {
  font-size: 48px;
  color: #ff9800;
}

.delete-text p {
  margin: 0 0 8px;
  font-size: 16px;
  color: #333;
}

.delete-count {
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-container {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-left {
    justify-content: flex-start;
  }

  .header-actions {
    justify-content: center;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .batch-right {
    justify-content: center;
  }

  .favorites-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .item-meta {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .item-actions {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>
